package org.linlinjava.litemall.admin.job;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.CouponConstant;
import org.linlinjava.litemall.db.util.CouponUserConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时更新用户的折扣
 */
@Component
public class DiscountJob {
    private final Log logger = LogFactory.getLog(DiscountJob.class);

    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallCompanyMemberService memberService;

    @Autowired
    private LitemallCompanyService companyService;

    /**
     * 每隔30分钟检查
     * TODO
     * 注意，因为是相隔一个小时检查，因此导致优惠券真正超时时间可能比设定时间延迟1个小时
     */
    @Scheduled(fixedDelay = 30 * 60 * 1000)
    public void updateDiscount() {
        logger.info("系统开启任务检查是否有企业更新折扣");
        List<LitemallCompany> companyList = companyService.queryNearyUpdate();
        for(int i = 0; i < companyList.size(); i ++){
            LitemallCompany company = companyList.get(i);
            List<LitemallCompanyMember> members = memberService.queryByCompanyId(company.getId());
            for (int j = 0; j < members.size(); j++) {
                LitemallCompanyMember member = members.get(j);
                List<LitemallUser> userList = userService.queryByMobile(member.getTelephone());
                for (int k = 0; k < userList.size(); k++) {
                    LitemallUser user = userList.get(k);
                    user.setDiscount(company.getDiscount());
                    userService.updateById(user);
                }
            }
        }
        logger.info("系统结束任务检查是否有企业更新折扣");
    }

}
